using System.Collections.Generic;
using EPiServer.Core;

namespace EPiSugar.EntityAdapter
{
    /// <summary>
    /// Wraps the creation of a mapped page entity and stores the created entity during the mappers lifetime.
    /// </summary>
    /// <typeparam name="T">The entity type expected for this mapper.</typeparam>
    public class EntityContext<T> where T: class 
    {
        private T instance;
        private readonly EntityModel model;
        private readonly IPageSource pageSource;

        public EntityContext() : this(EPiSugar.Current.Model, EPiSugar.Current.PageSource)
        {
        }

        public EntityContext(IPageSource page) : this(EPiSugar.Current.Model, page)
        {
        }

        public EntityContext(EntityModel model, IPageSource pageSource)
        {
            this.model = model;
            this.pageSource = pageSource;
        }


        public T Current
        {
            get { return instance ?? (instance = model.GetEntity(pageSource.CurrentPage) as T); }
            set { instance = value; }
        }


        public EntityT Get<EntityT>(PageReference pageLink) where EntityT: class 
        {
            return model.GetEntity(pageSource.GetPage(pageLink)) as EntityT;
        }

        public IEnumerable<EntityT> Children<EntityT>(PageReference parentLink) where EntityT: class
        {
            foreach (PageData page in pageSource.GetChildren(parentLink))
            {
                EntityT entity = model.GetEntity(page) as EntityT;
                if(entity != null)
                    yield return entity;
            }
        }
    }
}
